package com.cduestc.weatheractivity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import  android.app.Activity;

import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Html;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cduestc.sqllite.MySqlLite;
import com.cduestc.tools.GetDataFromNet;
import com.cduestc.tools.LocationData;
import com.cduestc.animation.ExitApp;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

public class HomePage extends Activity {

    private ImageButton ibSetting, ibReload;
    private TextView tvNotice, tvWeather, tvCityName, tvLifeIndex, tvLifeIndex2, tvWeatherT1, tvWeatherT2, tvWeatherT3, tvWeatherT4, tvWeatherT5, tvWeatherT6;
    private static final String REQUEST_PATH = "http://t.weather.itboy.net/api/weather/city/";
    private static String data;
    private Button btnShowMore;
    private String cityName;
    private static boolean isConnected;
    private double longitude = 0.0;   //经度
    private double latitude = 0.0;   //纬度
    private String showData;
    private String showNotice;
    private Handler handler = null;
    LocationManager locationManager = null;
    LocationData locationData = new LocationData(HomePage.this);
    String lifeIndex,lifeIndex2;
    int flagId = 0;
    TextView[] tvWeathers;
    //LocationListener locationListener = null;
    String cityIds = "";
    public static boolean isIsConnected() {
        return isConnected;
    }

    String[] cityCopy1;
    String[] codeCopy1;
    List<String> list = new ArrayList<>();

    private MySqlLite mySqlLite;
    SQLiteDatabase sdb;


    public static void setIsConnected(boolean isConnected) {
        HomePage.isConnected = isConnected;
    }

    SharedPreferences sharedFirst,shareMyLocalCity;
    PopupWindow flag = null;
    String myNowPosition = "";
    String[] futureData = {"", "", "", "", "", ""};
    private Handler handler1 = new Handler();

    Handler handler123 = new Handler();

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {

        }
        @Override
        public void onProviderEnabled(@NonNull String provider) {

        }

        @Override
        public void onProviderDisabled(@NonNull String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }
    };

    String realProvider = "";

    ConnectivityManager connectivityManager;
    GetDataFromNet getData = new GetDataFromNet();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApp exitApp = ExitApp.getInstance();
        exitApp.addActivity(this);
        setContentView(R.layout.activity_home_page);
        //使用流量提示
        sharedFirst = this.getSharedPreferences("TrafficWarning",MODE_PRIVATE);
        boolean dialog = false; //false显示   //true不显示
        GainData gd = new GainData();
        //当前定位 保存 首页天气显示
        shareMyLocalCity = this.getSharedPreferences("LocalCity",MODE_PRIVATE);

        //从缓存中拿到首显城市
        String s = shareMyLocalCity.getString("TheFirst","");
        if(!s.equals("")){
            myNowPosition = s;
            cityIds = s;
        }

        //本次免提示
        String state1 = sharedFirst.getString("Once", "");
        String state2 = sharedFirst.getString("Final","");

        // 从array.xml 中拿取城市和对应id信息
        Resources res = getResources();
        String[] city = res.getStringArray(R.array.city_name);
        String[] code = res.getStringArray(R.array.city_code);

        cityCopy1 = city;
        codeCopy1 = code;

        if(!cityIds.equals("")){
            for(int a = 0;a < cityCopy1.length ; a++){

                if(cityIds.equals(cityCopy1[a])){
                    flagId = a;
                    break;
                }else{
                    flagId = 3;
                }
            }
        }else{
            flagId = 3;
        }

        System.out.println("=====" + flagId);

        if(!state1.equals("")){
            dialog = true;
        }

        if(!state2.equals("")){
            dialog = true;
        }

        handler = new Handler();

        ibSetting = this.findViewById(R.id.ibSetting);
        tvWeather = this.findViewById(R.id.tvWeather);
        tvCityName = this.findViewById(R.id.tvCityName);
        tvWeatherT1 = this.findViewById(R.id.tvWeatherT1);
        tvWeatherT2 = this.findViewById(R.id.tvWeatherT2);
        tvWeatherT3 = this.findViewById(R.id.tvWeatherT3);
        tvWeatherT4 = this.findViewById(R.id.tvWeatherT4);
        tvWeatherT5 = this.findViewById(R.id.tvWeatherT5);
        tvWeatherT6 = this.findViewById(R.id.tvWeatherT6);
        tvNotice = this.findViewById(R.id.tvNotice);
        ImageButton ibPosition = this.findViewById(R.id.ibPosition);
        ibReload = this.findViewById(R.id.ibReload);
        Context context = HomePage.this;
        tvLifeIndex = this.findViewById(R.id.tvLifeIndex);
        tvLifeIndex2 = this.findViewById(R.id.tvLifeIndex2);
        btnShowMore = this.findViewById(R.id.btnShowMore);
        mySqlLite = new MySqlLite(this,"c1",null,1);
        sdb = mySqlLite.getWritableDatabase();


        btnShowMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(HomePage.this);
                Cursor cursor = sdb.query("mycitys",new String[]{"_id","cid","cityname"},null,null,null,null,null);
                if(cursor.getCount() == 0){
                    Toast.makeText(HomePage.this, "当前没有添加其它城市", Toast.LENGTH_SHORT).show();
                    return;
                }
                while(cursor.moveToNext()){
                    int cid = cursor.getInt(0);
                    String ccId = cursor.getString(1);
                    String ccName = cursor.getString(2);
                    list.add(ccName);
                }
                String[] s = new String[list.size()];
                for(int x = 0;x < list.size(); x++){
                    s[x] = list.get(x);
                    Log.i("223",s[x]);
                }

                builder.setIcon(R.drawable.icon_set2)
                        .setTitle("查看其它")
                        .setCancelable(false)
                        .setItems(s, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                for(int y = 0; y < cityCopy1.length ; y++){
                                    if(s[i].equals(cityCopy1[y])){
                                        flagId = y;
                                        for(int m = 0; m < s.length;m++){
                                            s[m] = "";
                                            list.clear();
                                        }
                                        Toast.makeText(HomePage.this, "数据加载成功", Toast.LENGTH_SHORT).show();
                                        gd.run();
                                        break;
                                    }
                                }

                            }
                        })
                        .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                for(int m = 0; m < s.length;m++){
                                    s[m] = "";
                                    list.clear();
                                }
                                dialogInterface.dismiss();
                            }
                        })
                        .create()
                        .show();
            }
        });

        //页面刷新
       ibReload.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               onCreate(null);
           }
       });

        tvWeathers = new TextView[]{tvWeatherT1, tvWeatherT2, tvWeatherT3, tvWeatherT4, tvWeatherT5, tvWeatherT6};

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> provider = locationManager.getProviders(true);

        //检查网络是否连接
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
            setIsConnected(true);
        } else {
            setIsConnected(false);
        }

        //判断网络类型
        String netType = "";
        if (isConnected == true) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                //wifi网络
                netType = "WiFi";
                //Toast.makeText(HomePage.this, "WiFi网络已连接", Toast.LENGTH_SHORT).show();
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                //移动网络
                netType = "Mobile";

                if(dialog == false) {
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(HomePage.this);
                    View viewWarn = View.inflate(HomePage.this, R.layout.activity_first_use, null);

                    CheckBox cbSwitchFinal;
                    cbSwitchFinal = viewWarn.findViewById(R.id.cbSwitchFinal);

                    builder1.setIcon(R.drawable.icon_warning)
                            .setTitle(" 警告")
                            .setView(viewWarn)
                            .setCancelable(false)
                            .setPositiveButton("继续使用", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    if (cbSwitchFinal.isChecked()) {
                                        SharedPreferences.Editor seFinal = sharedFirst.edit();
                                        seFinal.putString("Final", "final");
                                        seFinal.commit();
                                    } else {
                                        SharedPreferences.Editor seOnce = sharedFirst.edit();
                                        seOnce.putString("Once", "once");
                                        seOnce.commit();
//                                        Toast.makeText(HomePage.this, "本次使用将不会提示，但是下次打开会提示", Toast.LENGTH_SHORT).show();
                                    }
                                    dialogInterface.dismiss();
                                }
                            })
                            .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //wifi界面
//                                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
//                                startActivity(intent);
                                    //应用详细界面
//                                Uri packageUri = Uri.parse("package:" + "com.cduestc.weatheractivity");
//                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,packageUri);
//                                startActivity(intent);
                                    //应用权限界面   (还有报错，待处理)
//                                Intent intent = new Intent();
//                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                if(Build.VERSION.SDK_INT >= 9){
//                                    intent.setAction("android.setting.APPLICATION_DETAILS_SETTINGS");
//                                    intent.setData(Uri.fromParts("package:",context.getPackageName(),null));
//                                }else if(Build.VERSION.SDK_INT <= 8){
//                                    intent.setAction(Intent.ACTION_VIEW);
//                                    intent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
//                                    intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
//                                }
//                                startActivity(intent);
                                    //退出应用
                                    exitApp.onLowMemory();
                                    exitApp.exit();
                                }
                            })
                            .create()
                            .show();
                }
            }
        } else {
            Toast.makeText(HomePage.this, "网络似乎产生了一点问题......", Toast.LENGTH_SHORT).show();
        }

        gd.run();
        //获取定位信息
        ibPosition.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                class MyTask extends AsyncTask {

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();

                        if (provider.contains(LocationManager.GPS_PROVIDER)) {
                            realProvider = LocationManager.GPS_PROVIDER;
                        } else if (provider.contains(LocationManager.NETWORK_PROVIDER)) {
                            realProvider = LocationManager.NETWORK_PROVIDER;
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(HomePage.this);
                            builder.setIcon(R.drawable.icon_set2)
                                    .setTitle("提示")
                                    .setMessage("请打开位置服务，和位置访问权限")
                                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            Intent intent = new Intent();
                                            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivity(intent);
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            Toast.makeText(HomePage.this, "无法获取定位信息", Toast.LENGTH_SHORT).show();
                                            dialogInterface.dismiss();
                                        }
                                    })
                                    .create()
                                    .show();
                            return;
                        }
                        flag = showLoad(view);
                    }

                    @Override
                    protected Object doInBackground(Object[] objects) {
                        //避免阻塞，新建线程
                        new Thread(){
                            @Override
                            public void run() {
                                super.run();
                                getLocation(provider, locationManager, locationListener, locationData);
                                //显示当前定位信息数据
                                gd.run();
                                //将当前定位信息定为首先显示

                                if(myNowPosition.equals("")){
                                    return;
                                }

                                if(!myNowPosition.equals(cityIds)) {
                                    handler1.post(runnable111);
                                }

                            }
                        }.start();
                        return null;
                    }

                    @Override
                    protected void onCancelled() {
                        super.onCancelled();
                    }
                }
                new MyTask().execute();
            }
        });

        //设置
        ibSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDia(v);
            }
        });
    }

    //处理定位提示，是否将其设置为首显城市
    Runnable runnable111 = new Runnable() {

        @Override
        public void run() {

            AlertDialog.Builder builder1 = new AlertDialog.Builder(HomePage.this);
            builder1.setIcon(R.drawable.icon_warning)
                    .setTitle(" 提示")
                    .setCancelable(false)
                    .setMessage("是否将当前定位城市设置为首显城市")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            SharedPreferences.Editor sePosition = shareMyLocalCity.edit();
                            sePosition.putString("TheFirst", myNowPosition);
                            sePosition.commit();
                            Toast.makeText(HomePage.this, "成功设置" + myNowPosition + "为首显城市", Toast.LENGTH_SHORT).show();
                            myNowPosition = "";
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            myNowPosition = "";
                            dialogInterface.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
    };


    Runnable runableUi = new Runnable() {
        @Override
        public void run() {
            tvCityName.setText(cityName);
            tvNotice.setText(showNotice);
            if(isConnected == true) {
                tvLifeIndex.setText(Html.fromHtml(lifeIndex));
                tvLifeIndex2.setText(Html.fromHtml(lifeIndex2));
                tvWeather.setText(Html.fromHtml(showData));
            }else{
                tvLifeIndex.setText("请检查网络连接");
                tvLifeIndex2.setText("请检查网络连接");
                tvWeather.setText("请检查网络连接");
            }
            int a = 0;
            for (TextView t : tvWeathers) {
                t.setText(futureData[a]);
                a++;
            }
        }
    };

    //处理网络数据  使用内部类，方便获取成员变量
    class  GainData {
        public void run(){
            new Thread() {
                @Override
                public void run() {
                    String sendUrl = "";
                    if(cityIds.equals("")){
                        cityIds = "达州市";
                    }
                    if(myNowPosition.equals("")){
                        //默认未定位显示 达州市
                        if(!cityIds.equals("")){
                            sendUrl = REQUEST_PATH + codeCopy1[flagId];
                        }else {
                            sendUrl = REQUEST_PATH + 101270601;
                        }
                    }else{
                        sendUrl = REQUEST_PATH + codeCopy1[flagId];
                    }

                    data = getData.requestUrl(sendUrl, isConnected);
                    //解析json数据
                    if (data != null) {
                        JsonParser jsonParser = new JsonParser();
                        JsonObject jsonObject = jsonParser.parse(HomePage.data).getAsJsonObject();
                        JsonObject dataData = jsonObject.get("data").getAsJsonObject();

                        String timeData = jsonObject.get("time").getAsString();

                        JsonObject cityInfo = jsonObject.get("cityInfo").getAsJsonObject();

                        String city = cityInfo.get("city").getAsString();
                        cityName = city;
                        String cityCode = cityInfo.get("citykey").getAsString();
                        String parent = cityInfo.get("parent").getAsString();
                        String updateTime = cityInfo.get("updateTime").getAsString();

                        String joShiDu = dataData.get("shidu").getAsString();
                        String joPm25 = dataData.get("pm25").getAsString();
                        String joPm10 = dataData.get("pm10").getAsString();
                        String joQuality = dataData.get("quality").getAsString();
                        String joWenDU = dataData.get("wendu").getAsString();

                        JsonArray forecastData = dataData.get("forecast").getAsJsonArray();
                        JsonElement fd1 = forecastData.get(0);
                        JsonParser jsonParser1 = new JsonParser();
                        JsonObject jsonObject1 = jsonParser1.parse(String.valueOf(fd1)).getAsJsonObject();
                        String joDate = jsonObject1.get("date").getAsString();
                        String joNotice = jsonObject1.get("notice").getAsString();
                        String joHigh = jsonObject1.get("high").getAsString();
                        String cutHigh = joHigh.substring(2);
                        String joLow = jsonObject1.get("low").getAsString();
                        String cutLow = joLow.substring(2);
                        String joWeek = jsonObject1.get("week").getAsString();
                        String joSunRise = jsonObject1.get("sunrise").getAsString();
                        String joSunSet = jsonObject1.get("sunset").getAsString();
                        String joAqi = jsonObject1.get("aqi").getAsString();
                        String joFx = jsonObject1.get("fx").getAsString();
                        String joFl = jsonObject1.get("fl").getAsString();
                        String joType = jsonObject1.get("type").getAsString();

                        for (int i = 0; i <= 5; i++) {
                            JsonElement fds = forecastData.get(i + 1);
                            JsonParser jsonParser2 = new JsonParser();
                            JsonObject jsonObject2 = jsonParser2.parse(String.valueOf(fds)).getAsJsonObject();
                            String joHigh2 = jsonObject2.get("high").getAsString();
                            String joLow2 = jsonObject2.get("low").getAsString();
                            String joYmd2 = jsonObject2.get("ymd").getAsString();
                            String joWeek2 = jsonObject2.get("week").getAsString();
                            String joType2 = jsonObject2.get("type").getAsString();
                            futureData[i] = joYmd2 + " " + joWeek2
                                    + "\n" + "天气：" + joType2
                                    + "\n" + "温度：" + joHigh2 + " / " + joLow2;
                        }

                        showData = "<font color='red'><big>" + joWenDU +"</big><sup>&nbsp;℃</sup></font><br/><small>" + cutHigh + " / " + cutLow + "</small><br/><small>" + joType + "&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;" + "空气" + joQuality + "</small>";

                        lifeIndex = "<font color='blue'>空气质量</font>" + "<br/>" + "——————" + "<br/>" + "指数：" + joAqi + "<br/>" + "PM2.5：" + joPm25 + "<br/>" + "PM10：" + joPm10 + "<br/>";
                        lifeIndex2 = "<font color='blue'>其它信息</font>" + "<br/>" + "——————" + "<br/>" + "湿度：" + joShiDu + "<br/>" + "风力：" + joFl + "<br/>" + "风向：" + joFx + "<br/>" + "日升：" + joSunRise + "<br/>" + "日落：" + joSunSet;

                        showNotice = "提示信息：" + joNotice;

                    } else {
                        //cityName = "天气";
                        //showNotice = "网络未连接";
                    }
                    handler123.post(runableUi);

                }
            }.start();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(HomePage.this);
            builder.setIcon(android.R.drawable.stat_sys_warning)
                    .setTitle("提示")
                    .setMessage("确定要退出吗？")
                    .setCancelable(false)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            SharedPreferences.Editor seDel = sharedFirst.edit();
                            seDel.putString("Once","");
                            seDel.commit();
                            ExitApp exitApp = ExitApp.getInstance();
                            exitApp.onLowMemory();
                            exitApp.exit();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
        return false;
        //return super.onKeyDown(keyCode, event);
    }

    public PopupWindow showLoad(View view) {

        View viewMsg = View.inflate(HomePage.this, R.layout.progress_layout, null);
        TextView tvShowMsg = viewMsg.findViewById(R.id.tvShowMsg);
        //ProgressBar pbPosition = viewMsg.findViewById(R.id.pbPosition);

        tvShowMsg.setText("定位中，请稍候");

        System.out.println("=======================");
        PopupWindow popupWindow = new PopupWindow();

        popupWindow.setContentView(viewMsg);
        popupWindow.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setAnimationStyle(R.anim.pop_anima);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

        return popupWindow;
    }

    Runnable runnable123 = new Runnable() {
        @Override
        public void run() {
            if(myNowPosition.equals("")) {
                Toast.makeText(HomePage.this,"定位失败", Toast.LENGTH_SHORT).show();
                flag.dismiss();
                return;
            }
            tvNotice.setText(myNowPosition);
            Toast.makeText(HomePage.this,myNowPosition + " " + " 定位成功,正在更新数据", Toast.LENGTH_SHORT).show();
            flag.dismiss();
        }
    };

    Runnable runnable123123 = new Runnable() {
        @Override
        public void run() {
            tvNotice.setText(myNowPosition);
        }
    };

    public void getLocation(List<String> provider, LocationManager locationManager,LocationListener locationListener, LocationData locationData){
        if (realProvider.equals("gps")) {
            if (ActivityCompat.checkSelfPermission(HomePage.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(HomePage.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                System.out.println(latitude + " " + longitude);

                myNowPosition = locationData.getLocationName(longitude, latitude);

                for(int i = 0; i < cityCopy1.length; i++){
                    if(myNowPosition.equals(cityCopy1[i])){
                        handler123.post(runnable123123);
                        flagId = i;
                        //Log.i("557",codeCopy1[flagId]);
                    }
                }
                if(myNowPosition.equals("获取定位信息失败")){
                    myNowPosition = "";
                }
                //Looper.prepare();
                handler1.post(runnable123);
                //Looper.loop();
                locationManager.removeUpdates(locationListener);
            } else {
                handler1.post(runnable1234);
            }

        } else if (realProvider.equals("network")) {
            Location location1 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location1 != null) {
                latitude = location1.getLatitude();
                longitude = location1.getLongitude();
                System.out.println(latitude + " " + longitude);

                myNowPosition = locationData.getLocationName(longitude, latitude);
                System.out.println(myNowPosition);

                handler1.post(runnable123);

                locationManager.removeUpdates(locationListener);
            } else {
                handler1.post(runnable1234);
            }
        }
    }

    //请求更新位置信息
    Runnable runnable1234 = new Runnable() {

        @Override
        public void run() {
            if (ActivityCompat.checkSelfPermission(HomePage.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(HomePage.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(HomePage.this, "请打开位置权限", Toast.LENGTH_SHORT).show();
                return;
            }
            if (realProvider == "gps") {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 60 * 1000, 100, locationListener);
            }else if(realProvider == "network"){
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100, locationListener);
            }
        }
    };

    public void showDia(View v){
        View view1 = LayoutInflater.from(HomePage.this).inflate(R.layout.activity_setting,null);
        PopupWindow popupWindow = new PopupWindow();
        popupWindow.setOutsideTouchable(false);

        popupWindow.setContentView(view1);
        popupWindow.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setAnimationStyle(R.style.setting_animation);
        popupWindow.showAtLocation(v,Gravity.BOTTOM,0,0);

        TextView tvCancel,tvMgeCity,tvMore;

        tvCancel= view1.findViewById(R.id.tvCancel);
        tvMgeCity = view1.findViewById(R.id.btnMgeCity);
        tvMore = view1.findViewById(R.id.tvMore);

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });

        tvMgeCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomePage.this,ManageCity.class);
                startActivity(intent);
            }
        });

        tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomePage.this,More.class);
                startActivity(intent);
            }
        });
    }
}
